//#include <QGuiApplication>
#include <QApplication>
#include <QQuickWindow>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QScreen>
#include <QDBusConnection>
#include <QDebug>

#include "control.h"
#include "virtualkeyboard.h"

template <typename T>
inline T min(const T &a, const T&b) {
    return a<b ?a: b;
}

int main(int argc, char *argv[])
{
    qDebug() << "use qvk:" << qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));

    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QApplication app(argc, argv);
    //app.setQuitOnLastWindowClosed(false);





    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);

    engine.load(url);

    QQuickWindow *qqwin = qobject_cast<QQuickWindow *>(engine.rootObjects()[0]);
    QObject *edit = qqwin->findChild<QObject*>("preEdit");
    Control c(qqwin, edit);
#if 1
    VirtualKeyboard vk(&c);

    bool result;
    QDBusConnection session = QDBusConnection::sessionBus();
    result = session.registerService("com.deepin.VirtualKeyboard");
    if (!result) {
        qWarning() << "register service failed";
        return -1;
    }
    result = session.registerObject("/com/deepin/VirtualKeyboard", &c);
    if (!result) {
        qWarning() << "register object failed";
        return -1;
    }

#endif //
    QObject::connect(qqwin->screen(), &QScreen::geometryChanged, [qqwin](const QRect rect) {
        int w = min(rect.height()*16/15, rect.width());
        int h = w*3/8;
        int x = (rect.width()-w)/2;
        int y = rect.height()-h;
        qqwin->setProperty("width", w);
        qqwin->setProperty("height", h);
        qqwin->setProperty("x", x);
        qqwin->setProperty("y", y);

    });
    return app.exec();
}
